<template>
  <div class="home">
    <h1>list组件</h1>
    <!-- 头部 -->
    <div>
       <input type="text" @keydown.enter="add" v-model="keyword" >
    </div>
    <!-- 主题内容 -->
    <ul>
      <li v-for="(item,index) in list" :key="item.id">
        <input type="checkbox" v-model="item.checked">{{item.name}} <button @click="del(index)">删除</button>
      </li>
    </ul>
    <!-- 底部 -->
    <div>
      <div>完成：{{totalchecked}}个</div>
      <div>总共：{{total}}个</div>
    </div>
  </div>
</template>

<script>
import { nanoid } from "nanoid";
export default {
  name: "HomeView",
  data() {
    return {
      list: [],
      keyword: ""
    };
  },
  computed: {
    // 总共数量
    total() {
      return this.list.length;
    },
    // 完成数量
    totalchecked() {
      var result = this.list.reduce((total, item) => {
        if (item.checked) {
          return total += 1;
        } else {
          return total;
        }
      }, 0);
      return result;
    }
  },
  methods: {
    // 回车添加
    add() {
      var obj = { id: nanoid(), name: this.keyword, checked: false };
      this.list.unshift(obj);
      localStorage.setItem("list", JSON.stringify(this.list));
      this.keyword = "";
    },
    // 删除
    del(index) {
      this.list.splice(index, 1);
      localStorage.setItem("list", JSON.stringify(this.list));
    }
  },
   created() {
    var arr = JSON.parse(localStorage.getItem("list")) || [];
    this.list=arr
  },
};
</script>
